import { Map, View, Collection } from "ol";
import * as proj from 'ol/proj';
import { Group, Tile } from "ol/layer"
import * as control from 'ol/control';
import OLCesium from 'olcs/OLCesium.js';
import * as tilegrid from 'ol/tilegrid';
import TGWMTS from 'ol/tilegrid/WMTS';
import { WMTS } from 'ol/source';
import * as extent from 'ol/extent';

function SworldMap(options) {
     //二维地图初始化地图
     this._base2DLayer = new Group({
        layers: []
    });
    this._base2DLayer.name = '';
    //底图标签
    this._base2DLayer.isBaseLayer = true;
    //默认为三维地图
    this.isD3Map = false;
}

/**
 * 获取瓦片源数据对象
 * @param {object} urlModel 瓦片参数
 * @returns 
 */
SworldMap.prototype.getSource = function (urlModel) {
    var source = null;
    var projection = proj.get('EPSG:3857');
    if (urlModel.project) {
        projection = proj.get(urlModel.project);
    }

    //切片方案,有配置最大或最小比例层级时，定制对应的切片方案，只显示那几级
    var tileGrid = (urlModel.maxZoom !== undefined || urlModel.minZoom !== undefined) ?
        tilegrid.createXYZ({
            extent: projection.getExtent(),
            maxZoom: urlModel.maxZoom,
            minZoom: urlModel.minZoom,
            tileSize: urlModel.tileSize
        }) : undefined;

    switch (urlModel.type) {
        case "WMTS":
            var projectionExtent = projection.getExtent();
            var size = extent.getWidth(projectionExtent) / 256;
            var level_vol = urlModel.zoomVolatility || 0;//级别上下浮动值
            var gridName = urlModel.gridName || '';//geoserver gridName
            var resolutions = new Array(14);
            var matrixIds = new Array(14);
            for (var z = 0; z < 18; ++z) {
                resolutions[z] = size / Math.pow(2, z);
                matrixIds[z] = gridName + (z + level_vol);
            }
            source = new WMTS({
                url: urlModel.url,
                layer: urlModel.layer,
                matrixSet: urlModel.matrixSet,
                format: urlModel.format,
                projection: urlModel.projection || projection,
                tileGrid: urlModel.tileGrid || new TGWMTS({
                    origin: extent.getTopLeft(projectionExtent),
                    resolutions: resolutions,
                    matrixIds: matrixIds
                }),
                style: urlModel.style,
                wrapX: true,
                crossOrigin: 'anonymous',
                tileLoadFunction: urlModel.tileLoadFunction,
                dimensions: {
                    'tk': urlModel.tk
                }
            });
            break;
    }
    return source;
}

/**
 * 加载地图瓦片图层
 */
SworldMap.prototype._load2DBaseLayers = function () {
    var _baseMap2DUrls = [{
        name: "天地图WGS84卫星影像图",
        url: 'http://t{0-7}.tianditu.gov.cn/img_c/wmts?',
        layer: 'img',
        matrixSet: 'c',
        format: 'tiles',
        style: 'default',
        maxZoom: this._mapMaxZoom,
        type: 'WMTS',
        project: "EPSG:4326",
        tk: '40f8a6ef26bf1949696cc66672370b31'
    }, {
        name: "天地图WGS84卫星影像标签",
        url: 'http://t{0-7}.tianditu.gov.cn/cia_c/wmts?',
        layer: 'cia',
        matrixSet: 'c',
        format: 'tiles',
        style: 'default',
        maxZoom: this._labelMaxZoom,
        type: 'WMTS',
        project: "EPSG:4326",
        tk: '40f8a6ef26bf1949696cc66672370b31'
    }];
    //清空已有底图
    this._base2DLayer.getLayers().clear();
    //添加新底图
    var layers = [];
    for (var i = 0; i < _baseMap2DUrls.length; i++) {
        var dataSource = this.getSource(_baseMap2DUrls[i]);
        var tileGrid = dataSource.getTileGrid();
        var layer = new Tile({
            source: dataSource,
            maxZoom: 30
        });
        layer.name = _baseMap2DUrls[i].name ? _baseMap2DUrls[i].name : "";
        layers.push(layer);
    }
    this._base2DLayer.setLayers(new Collection(layers));
}

SworldMap.prototype.initMap = function () {
    this._load2DBaseLayers();
    //初始化二维地图
    this._d2map = new Map({
        controls: control.defaults({
            zoom: false,
            attribution: false,
            rotate: false
        }),
        layers: [this._base2DLayer],
        target: "map",
        view: new View({
            center: proj.transform([104, 31], 'EPSG:4326', 'EPSG:4326'),
            zoom: 0,
            projection: 'EPSG:4326',
            minZoom: 0,
            maxZoom: 18
        }),
        logo: false,
    });
    
    var map3dContainer = null;
    //附加三维地图（负责三维地图创建、同步）
    // this._d3map = new OLCesium({
    //     map: this._d2map,
    //     terrainExaggeration: 0,
    //     target: map3dContainer
    // });


    const ol3d = new OLCesium({map:  this._d2map}); // ol2dMap 是openlayers绑定的地图对象
    ol3d.setEnabled(true);//3维地形切换
}

/**
 * 二三维切换
 * @date 2023-03-30
 * @returns {any}
 */
SworldMap.prototype.switchMap = function () {
    let b = (this.isD3Map) ? false : true;
    // let b=false
    // console.log(b)
    this._d3map.setEnabled(b);
}

export default SworldMap;
